<template>
    <div>
        <!-- <div>我是主界面</div> -->
        
        <a-button type="primary" @click="openITK">打开ITK</a-button>
        <a-button type="primary" @click="openImageFile">图片</a-button>
        <a-button type="primary" @click="getPolicy">获取上传policy</a-button>
    </div>
    <div class="clearfix">

        <!-- <form  action="https://abus.oss-cn-hangzhou.aliyuncs.com" method="post" enctype="multipart/form-data">
                <input type="text" name="OSSAccessKeyId" value="LTAI5tPboUStAJYroo16tkTJ">
                <br>
                <input type="text" name="policy" value="eyJleHBpcmF0aW9uIjoiMjAyNC0wMy0zMFQxNTo1MzowNS4xNTJaIiwiY29uZGl0aW9ucyI6W1siY29udGVudC1sZW5ndGgtcmFuZ2UiLDAsNTI0Mjg4MDAwXSxbInN0YXJ0cy13aXRoIiwiJGtleSIsInRlbXBcLyJdXX0=">
                <br>
                <input type="text" name="Signature" value="8W8HJ7Tjb/4/QVNebr/8JW3irH4=">
                <br>
                <input type="text" name="key" value="temp/1234">
                <br>
                <input type="text" name="callback" value="eyJjYWxsYmFja0JvZHlUeXBlIjoiYXBwbGljYXRpb24vanNvbiIsImNhbGxiYWNrVXJsIjoiaHR0cDovLzExMi4xMjQuMzUuMjM2OjgwODAvYWJ1c2FwcC92MS9maWxlTWFuYWdlL29zc0NhbGxiYWNrIiwiY2FsbGJhY2tCb2R5Ijoie1wiYnVja2V0XCI6JHtidWNrZXR9LFwib2JqZWN0XCI6JHtvYmplY3R9LFwibWltZVR5cGVcIjoke21pbWVUeXBlfSxcInNpemVcIjoke3NpemV9LFwiY29udGVudE1kNTpcIjoke2NvbnRlbnRNZDV9LFwiZXRhZ1wiOiR7ZXRhZ319In0=">
                # 设置上传成功后跳转的页面，可替换为实际页面。
                <br>
                <input type="text" name="success_action_redirect" value="#">
                # 设置上传成功后返回的状态码为201，状态码支持自定义。
                <br>
                <input type="text" name="success_action_status" value="200">
                <br>
                <input name="file" type="file" id="file">
                <br>
                <input name="submit" value="Upload" type="submit">
            </form> -->

    </div>

    <div>
        <a-form :model="formState" name="basic" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }" autocomplete="off"
            @finish="onFinish">
            <a-form-item label="OSSAccessKeyId" name="OSSAccessKeyId">
                <a-input v-model:value="formState.OSSAccessKeyId" />
            </a-form-item>

            <a-form-item label="policy" name="policy">
                <a-input v-model:value="formState.policy" />
            </a-form-item>

            <a-form-item label="Signature" name="Signature">
                <a-input v-model:value="formState.Signature" />
            </a-form-item>


            <a-form-item label="key" name="key">
                <a-input v-model:value="formState.key" />
            </a-form-item>


            <a-form-item label="callback" name="callback">
                <a-input v-model:value="formState.callback" />
            </a-form-item>


            <a-form-item label="success_action_redirect" name="success_action_redirect">
                <a-input v-model:value="formState.successActionRedirect" />
            </a-form-item>

            <a-form-item label="success_action_status" name="success_action_status">
                <a-input v-model:value="formState.successActionStatus" />
            </a-form-item>


            <!-- <a-form-item
      label="success_action_redirect"
      name="success_action_redirect"
    >
      <a-input v-model:value="formState.successActionRedirect" />
    </a-form-item> -->


            <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
                <a-button type="primary" html-type="submit">Submit</a-button>
            </a-form-item>



        </a-form>
    </div>
    <img :src="imgSrc">

    <!-- <a-upload
    v-model:file-list="fileList"
    name="file"
    action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
    :headers="headers"
    @change="handleChange"
  >
    <a-button>
      <upload-outlined></upload-outlined>
      Click to Upload
    </a-button>
  </a-upload> -->

</template>
<script setup>

import { ref, reactive, computed, onMounted } from 'vue';
import { useRouter, } from 'vue-router'
import { getUserInfo, getDownloadPolicy } from '@/api/user';
import { message } from 'ant-design-vue';

import axios from 'axios';

const imgSrc = ref("");

// const router = useRouter();

var uploadFile;

const formState = reactive({
    OSSAccessKeyId: '',
    policy: '',
    Signature: '',
    key: '',
    callback: '',
    successActionRedirect: '#',
    successActionStatus: '200',
    host: ''

});

// const logout = () => {
//     let tokenInfo = useTokenInfoStore()
//     tokenInfo.clearToken()
//     router.go(0)
// }

// const getInfo = async () => {
//     let result = await getUserInfo();
//     if (!result) {
//         message.error('获取用户信息失败，请重新登录');
//         setTimeout(() => {
//             router.push("/login");
//         }, 2000);

//     } else {
//         // console.log(result)
//     }
// }


const openITK = () => {
    window.electronAPI.openITK("123");
}

const openImageFile = () => {
    window.electronAPI.openImageFile();
}

window.electronAPI.handlerSnapShot((_event, value) => {
    // console.log(value)
    const { filePath, fileData } = value
    const fileName = filePath.split('/').reverse()[0];
    let file = new File([fileData], fileName, { type: 'image/' + filePath.split('.').reverse()[0] })
    uploadFile = file;
    // console.log(file)

    formState.key = 'temp/' + fileName;

    const reader = new FileReader();
    reader.onload = function () {
        const base64String = reader.result;
        // console.log(base64String);
        imgSrc.value = base64String
    }
    // reader.readAsArrayBuffer(file);
    reader.readAsDataURL(file);
})



const getPolicy = async () => {
    let result = await getDownloadPolicy();
    if (result) {
        // console.log(result);
        formState.OSSAccessKeyId = result.data.accessid;
        formState.Signature = result.data.signature;
        formState.policy = result.data.policy;
        formState.callback = result.data.callback;
        formState.host = result.data.host;
    }
}

onMounted(() => {
    // getInfo();
    // getPolicy();

})


const onFinish = (values) => {



    // console.log(values);

    var fd = getFormData(values)
    fd.append('file', uploadFile);
    axios.post(formState.host,fd,{
      headers:{
        'Content-Type': 'multipart/form-data'
      }
    })
    .then(response=>{
      console.log(response)
      message.success(`file uploaded successfully:${ JSON.stringify(response.data.data)}`);
    })
    .catch(error=>{
      console.log(error)
    })


}

// const handleChange = info => {
//   if (info.file.status !== 'uploading') {
//     console.log(info.file, info.fileList);
//   }
//   if (info.file.status === 'done') {
//     message.success(`${info.file.name} file uploaded successfully`);
//   } else if (info.file.status === 'error') {
//     message.error(`${info.file.name} file upload failed.`);
//   }
// };
// const fileList = ref([]);
// const headers = {
//   authorization: 'authorization-text',
// };

// function getBase64(file) {
//   return new Promise((resolve, reject) => {
//     const reader = new FileReader();
//     reader.readAsDataURL(file);
//     reader.onload = () => resolve(reader.result);
//     reader.onerror = error => reject(error);
//   });
// }
// const previewVisible = ref(false);
// const previewImage = ref('');
// const previewTitle = ref('');
// const fileList = ref([

// ]);

// const handleCancel = () => {
//   previewVisible.value = false;
//   previewTitle.value = '';
// };
// const handlePreview = async file => {
//   if (!file.url && !file.preview) {
//     file.preview = await getBase64(file.originFileObj);
//   }
//   previewImage.value = file.url || file.preview;
//   previewVisible.value = true;
//   previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1);
// };


function getFormData(object) {
    const formData = new FormData()
    Object.keys(object).forEach(key => {
        const value = object[key]
        if (Array.isArray(value)) {
            value.forEach((subValue, i) =>
                formData.append(key + `[${i}]`, subValue)
            )
        } else {
            formData.append(key, object[key])
        }
    })
    return formData
}

</script>